package com.kedacom.demo.healthcheck;

import javax.annotation.PostConstruct;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis健康检查
 * @author luocanfeng
 * @date 2016年9月5日
 */
public class RedisHealthCheckItem extends HealthCheckItem {

	private String redisHost;
	private int redisPort = 6379;
	private String redisPassword;

	private static String PONG = "PONG";
	private static JedisPool jedisPool = null;

	{
		type = Type.Redis;
	}

	public RedisHealthCheckItem() {
		type = Type.Redis;
	}

	public RedisHealthCheckItem(String name) {
		this();
		this.name = name;
	}

	public RedisHealthCheckItem(String name, String redisHost) {
		this(name);
		this.redisHost = redisHost;
	}

	public RedisHealthCheckItem(String name, String redisHost, int redisPort) {
		this(name, redisHost);
		this.redisPort = redisPort;
	}

	public RedisHealthCheckItem(String name, String redisHost, int redisPort, String redisPassword) {
		this(name, redisHost, redisPort);
		this.redisPassword = redisPassword;
	}

	@PostConstruct
	public void init() {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(1);
			config.setMaxIdle(1);
			config.setMaxWaitMillis(1000);
			config.setTestOnBorrow(true);
			jedisPool = redisPassword == null ? new JedisPool(config, redisHost, redisPort, 1000)
					: new JedisPool(config, redisHost, redisPort, 1000, redisPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 检查Redis是否正常
	 */
	@Override
	public boolean doCheck() {
		Jedis jedis = getJedis();
		String pong = jedis.ping();
		returnJedis(jedis);
		return PONG.equals(pong);
	}

	public static void main(String[] args) {
		RedisHealthCheckItem healthCheck = new RedisHealthCheckItem("Redis健康检查", "172.16.185.233", 6379);
		healthCheck.init();
		System.out.println(healthCheck.doCheck());
	}

	public synchronized static Jedis getJedis() {
		try {
			return jedisPool.getResource();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void returnJedis(final Jedis jedis) {
		if (jedisPool != null && jedis != null) {
			jedisPool.returnResourceObject(jedis);
		}
	}

	public String getRedisHost() {
		return redisHost;
	}

	public void setRedisHost(String redisHost) {
		this.redisHost = redisHost;
	}

	public int getRedisPort() {
		return redisPort;
	}

	public void setRedisPort(int redisPort) {
		this.redisPort = redisPort;
	}

	public String getRedisPassword() {
		return redisPassword;
	}

	public void setRedisPassword(String redisPassword) {
		this.redisPassword = redisPassword;
	}

}
